package com.gzc.just.play.last.war.loginserver.handler;

import com.gzc.just.play.last.war.common.handler.SimpleMessageHandler;
import com.gzc.just.play.last.war.loginserver.service.AuthService;
import io.netty.channel.ChannelHandlerContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Map;

/**
 * 注册消息处理器
 * 处理用户注册请求
 */
@Component
public class RegisterMessageHandler implements SimpleMessageHandler {
    private static final Logger logger = LoggerFactory.getLogger(RegisterMessageHandler.class);
    
    @Autowired
    private AuthService authService;
    
    private static final int REGISTER = 4003;
    
    @Override
    public void handle(Object message, ChannelHandlerContext ctx) throws Exception {
        // 从消息中解析注册信息
        String username = extractUsername(message);
        String password = extractPassword(message);
        String email = extractEmail(message);
        
        // 验证输入
        if (username == null || username.trim().isEmpty() || 
            password == null || password.trim().isEmpty() ||
            email == null || email.trim().isEmpty()) {
            sendRegisterResponse(ctx, null, false, "Username, password and email are required");
            return;
        }
        
        // 验证用户名和密码格式
        if (!validateUsername(username)) {
            sendRegisterResponse(ctx, null, false, "Invalid username format");
            return;
        }
        
        if (!validatePassword(password)) {
            sendRegisterResponse(ctx, null, false, "Password must be at least 6 characters");
            return;
        }
        
        if (!validateEmail(email)) {
            sendRegisterResponse(ctx, null, false, "Invalid email format");
            return;
        }
        
        // 进行注册
        Map<String, Object> registerResult = authService.register(username, password, email);
        
        // 检查注册结果
        boolean success = (Boolean) registerResult.getOrDefault("success", false);
        String messageStr = (String) registerResult.getOrDefault("message", "Registration failed");
        
        // 发送注册响应
        if (success) {
            logger.info("User {} registered successfully", username);
        } else {
            logger.warn("Registration failed for user: {}, reason: {}", username, messageStr);
        }
        
        sendRegisterResponse(ctx, registerResult, success, messageStr);
    }
    
    private String extractUsername(Object message) {
        // 实际实现中应该从消息对象中解析用户名
        // 这里返回示例值
        return "newuser";
    }
    
    private String extractPassword(Object message) {
        // 实际实现中应该从消息对象中解析密码
        // 这里返回示例值
        return "newpass123";
    }
    
    private String extractEmail(Object message) {
        // 实际实现中应该从消息对象中解析邮箱
        // 这里返回示例值
        return "newuser@example.com";
    }
    
    private boolean validateUsername(String username) {
        // 用户名验证规则：3-20个字符，只包含字母、数字和下划线
        return username != null && username.matches("^[a-zA-Z0-9_]{3,20}$");
    }
    
    private boolean validatePassword(String password) {
        // 密码验证规则：至少6个字符
        return password != null && password.length() >= 6;
    }
    
    private boolean validateEmail(String email) {
        // 邮箱验证规则：基本邮箱格式
        return email != null && email.matches("^[\\w.-]+@[\\w.-]+\\.[a-zA-Z]{2,}$");
    }
    
    private void sendRegisterResponse(ChannelHandlerContext ctx, Map<String, Object> registerResult, 
                                    boolean success, String message) {
        // 实际实现中应该构造并发送注册响应消息
        logger.info("Sending register response: success={}, message={}", success, message);
        
        // 示例：打印注册结果内容（实际实现中应该将结果序列化为响应消息）
        if (success && registerResult != null) {
            logger.debug("Register result content:");
            for (Map.Entry<String, Object> entry : registerResult.entrySet()) {
                if (!"password".equals(entry.getKey())) { // 不打印密码
                    logger.debug("{}: {}", entry.getKey(), entry.getValue());
                }
            }
        }
    }

    @Override
    public int getMessageId() {
        return REGISTER;
    }
    
    @Override
    public String getName() {
        return "RegisterMessageHandler";
    }
    
    @Override
    public Logger getLogger() {
        return logger;
    }
}